package com.thoughtworks.biblioteca.dao.file;

import com.thoughtworks.biblioteca.dao.MovieDao;
import com.thoughtworks.biblioteca.model.Movie;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


public class MovieFileDao implements MovieDao {
    private static final String NEW_MOVIE = "N/A";

    Movie getMovieFrom(String movieSummary) {
        String[] attr = movieSummary.split("[|]");

        int id = Integer.parseInt(attr[0].trim());
        String name = attr[1].trim();
        String director = attr[2].trim();
        String rate;
        try {
            rate = attr[3].trim();
        } catch (ArrayIndexOutOfBoundsException e) {
            rate = NEW_MOVIE;
        }
        if ("".equals(rate) || rate == null) {
            rate = NEW_MOVIE;
        }

        return new Movie(id, name, director, rate);
    }

    public List<Movie> getAllMovies() {
        List<Movie> movies = new ArrayList<Movie>();
        try {
            File f = new File("resources/movie.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(f)));
            String movieSummary;
            while ((movieSummary = br.readLine()) != null) {
                Movie tmpMovie = getMovieFrom(movieSummary);
                movies.add(tmpMovie);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return movies;
    }

    public Movie findMovieByMovieId(String movieId) {
        return null; 
    }
}
